<template>
  <RkContainer :isFooter="false"
    :isAside="isAside">
    <template #header_left></template>
    <template #header_right>
      <el-button type="primary"
        @click="onAddUserClick">新增</el-button>
      <el-button type="danger"
        @click.stop="handleOperation({id:'1'})">删除
      </el-button>
    </template>
    <template #aside>
      <RkAdAgTree :adTreeHidden="false"
        @toggleHidden="(hidden) => isAside = !hidden"
        @ad-node-click="handleAdNodeClick"
        @ag-node-click="handleAgNodeClick" />
    </template>
    <template #main>
      <rk-center>
        <template #content>
          <rk-grid ref="userTableRef"
            data-url="/user/pageList"
            title="用户管理"
            :columns="tableColumns"
            :params="queryParams"
            :boxConfig="true">
            <template #toolbar_title_buttons>
              <el-input v-model="queryParams.keyword"
                placeholder="请输入项目用户编码/用户名称/手机号码"
                style="width: 300px;"
                @input="handleSearch"
                clearable>
              </el-input>
            </template>
            <template #operation="{ row }">
              <el-row justify="space-around"
                align="middle">
                <el-button type="primary"
                  link
                  @click.stop="handleOperation({id:'0'},row)">修改
                </el-button>
                <el-dropdown>
                  <span class="el-dropdown-link">
                    更多操作
                    <el-icon class="el-icon--right">
                      <arrow-down />
                    </el-icon>
                  </span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item v-for="item in tableOperation[row.status]"
                        @click="handleOperation(item,row)">
                        {{ item.name }}
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </el-row>
            </template>
          </rk-grid>
        </template>
      </rk-center>
    </template>
    <user-add-edit ref="userAddEditRef"
      :ok="handleSearch" />
    <user-pwd-edit ref="userPwdEditRef" />
  </RkContainer>
</template>

<script setup>
import { useRoute } from 'vue-router'
import { operationColumn } from '@/config/column-config.js'
import { useContainerAside } from '@/hooks'
import { provide, reactive, readonly, ref } from "vue";
import UserAddEdit from "@/views/system/user/dialog/UserAddEdit.vue";
import { RkConfirmBox } from "@/components/message-box/index.js";
import UserPwdEdit from "@/views/system/user/dialog/UserPwdEdit.vue";
import { useUserStore } from '@/stores/modules';
import { USER_STATUS_ENUMS, USER_TYPE } from "@/enums/enums-system.js";
import { COMMON_STOP_OPEN_MT_ENUMS } from "@/enums/enums-common.js";
import { useUserApi } from "@/api/index.js";
import { ElMessage } from "element-plus";
import { ArrowDown } from '@element-plus/icons-vue'

const { userDelete, userResetPassword, userUpdateStatus } = useUserApi();
const userInfo = useUserStore().userInfo

// ----- 获取当前路由
const route = useRoute()
const userTableRef = ref(null)

// ----- 树结构操作
const { isAside } = useContainerAside()

// ----- 表格相关操作
const queryParams = reactive({
  keyword: "",
  userAgId: "",
  userId: "",
  agId: userInfo.agId,
  agCode: userInfo.agCode,
  adCode: userInfo.adCode,
})
const defaultParams = reactive({
  adName: userInfo.adName,
  adId: userInfo.adId,
  agName: '',
  agId: '',
  agCode: '',
  adCode: userInfo.adCode,
})
provide('treeParams', readonly(defaultParams))
const userAddEditRef = ref(null)
const userPwdEditRef = ref(null)
const tableColumns = ref([
  { field: 'code', title: '用户编码', width: 150, align: 'left' },
  { field: 'name', title: '用户名称', width: 150, align: 'left' },
  { field: 'roleName', title: '用户角色', width: 150, align: 'left' },
  { field: 'usertype', title: '用户类型', width: 150, align: 'center', formatter: ['enumsFormats', 'USER_TYPE'] },
  {
    field: 'status',
    title: '状态',
    width: 150,
    align: 'center',
    cellRender: { name: 'enumsRender', enumName: 'USER_STATUS_ENUMS', isTag: true }
  },
  { field: 'authName', title: '数据权限', width: 250, align: 'left' },
  { field: 'adName', title: '区划', width: 250, align: 'left' },
  { field: 'agencyName', title: '单位', width: 250, align: 'left' },
  { field: 'divisionName', title: '归口处室', width: 150, align: 'center' },
  { field: 'job', title: '职称', width: 150, align: 'center' },
  { field: 'phoneNumber', title: '手机号', width: 200, sortable: true, align: 'center' },
  { field: 'idCode', title: '身份证号码', width: 200, sortable: true, align: 'center' },
  { field: 'email', title: '电子邮件', width: 200, align: 'center' },
  operationColumn(150)
])

const tableOperation = ref({
  "1": [
    { id: "3", name: '停用' },
    { id: "5", name: '重置密码' },
    { id: "6", name: '修改密码' },
  ],
  '2': [
    { id: "4", name: '启用' },
    { id: "5", name: '重置密码' },
    { id: "6", name: '修改密码' },
  ]
})
const onAddUserClick = () => {
  userAddEditRef.value.handleOpen({ isEdit: false, data: {} })
}
const handleAdNodeClick = (obj) => {
  if (obj) {
    Object.assign(defaultParams, { adCode: obj.code, adId: obj.id, adName: obj.name, agCode: '', agId: '' })
    Object.assign(queryParams, { adCode: obj.code, agCode: '', agId: '' })
    handleSearch()
  }
}
const handleAgNodeClick = (obj) => {
  if (obj) {
    Object.assign(defaultParams, { agCode: obj.code, agName: obj.name, agId: obj.id })
    Object.assign(queryParams, { agCode: obj.code, agId: obj.id })
    handleSearch()
  }
}
const handleOperation = (item, row) => {
  if (item.id === '0') {
    userAddEditRef.value.handleOpen({ isEdit: true, data: row })
  } else if (item.id === '1') {
    const seleRows = userTableRef.value.getCheckboxRecords()
    if (seleRows.length === 0 || !seleRows) {
      ElMessage.warning("请至少一条数据进行修改操作！");
      return
    }
    let ids = seleRows.map(item => {
      return item.guid
    })
    RkConfirmBox({
      title: '提示', content: "确定要删除吗", onSubmit: () => {
        //删除
        userDelete({ userIds: ids.join(",") }).then(resp => {
          if (resp.code === 200) {
            ElMessage.success({ message: '删除成功' })
            handleSearch()
          } else {
            ElMessage.error({ message: '删除失败' })
          }
        })
      }
    })
  } else if (item.id === '3' || item.id === '4') {
    let params = { userIds: row.guid, status: '1' }
    if (item.id === '3') {
      params.status = '2'
    }
    RkConfirmBox({
      title: '提示', content: `确定要${item.name}吗`, onSubmit: () => {
        userUpdateStatus(params).then(resp => {
          if (resp.code === 200) {
            ElMessage.success({ message: `${item.name}成功` })
            handleSearch()
          } else {
            ElMessage.error({ message: `${item.name}失败` })
          }
        })
      }
    })
  } else if (item.id === '5') {
    RkConfirmBox({
      title: '提示', content: "请确认是否重置密码！", onSubmit: () => {
        //重置密码
        userResetPassword({ userId: row.guid }).then(resp => {
          if (resp.code === 200) {
            ElMessage.success({ message: "密码重置成功" })
            handleSearch()
          } else {
            ElMessage.error({ message: "密码重置失败" })
          }
        })
      }
    })
  } else if (item.id === '6') {
    userPwdEditRef.value.handleOpen(row)
  }
}

const handleSearch = () => {
  userTableRef.value.searchEvent()
}

</script>

<style lang="scss" scoped>
</style>
